<template>
  <div class="dialog-container">
    <el-dialog
      :title="dialogType==='add'?'添加客户':dialogType === 'detail'?'客户详情':'修改客户单位信息'"
      :visible="dialogVisible"
      @open="initData"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        v-loading="formLoading"
        :model="dataForm"
        class="dialog-form"
        :rules="rules"
        label-width="110px"
        size="mini"
        :disabled="dialogType === 'detail'"
      >
        <el-row>
          <el-tabs>
            <el-tab-pane label="企业基本信息">
              <el-col :span="12">
                <el-form-item label="企业名称" prop="name">
                  <el-input v-model="dataForm.name" placeholder="请输入企业名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业简称" prop="enterpriseShort">
                  <el-input v-model="dataForm.enterpriseShort" placeholder="请输入企业简称" />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="所属项目部" prop="projectDepartmentId">
                  <el-select v-model="dataForm.projectDepartmentId" class="w-100" placeholder="请选择所属项目部">
                    <el-option
                      v-for="(item,index) in projectDepartments"
                      :key="index+'projectDepartment'"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="排放类型" prop="emissionType">
                  <el-select v-model="dataForm.emissionType" class="w-100" placeholder="请选择排放类型">
                    <el-option
                      v-for="(item,index) in emissionTypes"
                      :key="index+'emissionType'"
                      :value="item.code"
                      :label="item.codeName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="控制级别" prop="controlLevel">
                  <el-select v-model="dataForm.controlLevel" class="w-100" placeholder="请选择控制级别">
                    <el-option
                      v-for="(item,index) in controlLevels"
                      :key="index+'controlLevel'"
                      :value="item.code"
                      :label="item.codeName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业类别" prop="industryCategory">
                  <el-select v-model="dataForm.industryCategory" class="w-100" placeholder="请选择行业类别">
                    <el-option
                      v-for="(item,index) in industryCategorys"
                      :key="index+'industryCategory'"
                      :value="item.code"
                      :label="item.codeName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="组织机构代码" prop="organizationCode">
                  <el-input v-model="dataForm.organizationCode" placeholder="请输入组织机构代码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人代表" prop="legalRepresentative">
                  <el-input v-model="dataForm.legalRepresentative" placeholder="请输入法人代表" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮编" prop="zipCode">
                  <el-input v-model="dataForm.zipCode" placeholder="请输入邮编" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="传真" prop="fax">
                  <el-input v-model="dataForm.fax" placeholder="请输入传真" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contacts">
                  <el-input v-model="dataForm.contacts" placeholder="联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" prop="contactInformation">
                  <el-input v-model="dataForm.contactInformation" placeholder="请输入联系方式" />
                </el-form-item>
              </el-col>
              <el-col :span="19">
                <el-form-item label="经纬度：">
                  <el-input v-model="dataForm.enterpriseLocation" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-button size="mini" @click="mapDialogVisible = true">点击地图</el-button>
              </el-col>
              <el-col :span="8">
                <el-form-item label="企业地址：">
                  <el-select v-model="dataForm.addressPId" @change="selectCity">
                    <el-option
                      v-for="(item, index) in provinceList"
                      :key="index+ '_province'"
                      :value="item.areaid"
                      :label="item.areaname"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-select v-model="dataForm.enterpriseCityId" @change="selectDistrict">
                    <el-option
                      v-for="(item, index) in cityList"
                      :key="index+ '_city'"
                      :value="item.areaid"
                      :label="item.areaname"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" label="">
                <el-form-item>
                  <el-select v-model="dataForm.enterpriseAddressId">
                    <el-option
                      v-for="(item, index) in districtList"
                      :key="index+ '_district'"
                      :value="item.areaid"
                      :label="item.areaname"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业地址详细" prop="enterpriseAddressDetails">
                  <el-input v-model="dataForm.enterpriseAddressDetails" placeholder="请输入企业地址详细" @blur="blur" />
                </el-form-item>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-form>
      <span v-if="dialogType !== 'detail' " slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleSave">保存</el-button>
        <el-button size="mini" class="cancel-btn" @click="closeDialog">取消</el-button>
      </span>
      <el-dialog
        title="地图"
        :visible.sync="mapDialogVisible"
        width="40%"
        append-to-body
        @opened="addMarker"
        @close="removeOverlay"
      >
        <el-form class="dialog-form" label-width="100px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="地理坐标：">
                <el-input v-model="coordinate" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <BaiduMap
          ref="map"
          @setPonit="setPonit"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="mapDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="selectMap()">确定</el-button>
        </span>
      </el-dialog>
    </el-dialog>

  </div>
</template>
<script>
import { getDict } from '@/utils/dict'
import BaiduMap from '@/components/BaiduMap/index'
import { add, edit } from '@/api/base/enterprise'
import BMap from 'BMap'
import { getList, getInfo } from '@/api/system/area'
// import { getList as getProjectDepartment } from '@/api/info/projectDepartment'

export default {
  name: 'AddDialog',
  components: {
    BaiduMap
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'detail'
    },
    obj: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      saveLoading: false,
      formLoading: false,
      dataForm: {
        id: null,
        name: null,
        enterpriseShort: null,
        // projectDepartmentId: null,
        organizationCode: null,
        legalRepresentative: null,
        zipCode: null,
        fax: null,
        contacts: null,
        contactInformation: null,
        emissionType: null,
        controlLevel: null,
        industryCategory: null,
        enterpriseLocation: null,
        enterpriseAddressDetails: null,
        addressPId: null,
        enterpriseCityId: null,
        enterpriseAddressId: null
      },
      enterpriseAddressDetails: '',
      // projectDepartments: [],
      emissionTypes: [],
      controlLevels: [],
      industryCategorys: [],
      dialogImageUrl: '',
      mapDialogVisible: false,
      coordinate: '',
      provinceList: [],
      cityList: [],
      districtList: [],
      rules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        // projectDepartmentId: [{ required: true, message: '请选择项目部', trigger: 'blur' }],
        enterpriseShort: [{ required: true, message: '请输入企业简称', trigger: 'blur' }],
        emissionType: [{ required: true, message: '请选择排放类型', trigger: 'blur' }],
        controlLevel: [{ required: true, message: '请选择控制级别', trigger: 'blur' }],
        industryCategory: [{ required: true, message: '请选择行业类别', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.emissionTypes = getDict('e012')
    this.controlLevels = getDict('e014')
    this.industryCategorys = getDict('e013')
    // getProjectDepartment().then(res => {
    //   this.projectDepartments = res.data.list
    // })
  },
  methods: {
    blur() {
      // 创建地址解析器实例
      var myGeo = new BMap.Geocoder()
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(this.dataForm.enterpriseAddressDetails, point => {
        if (point) {
          var po = point.lng + ',' + point.lat
          this.dataForm.enterpriseLocation = po
          console.log(po)
          console.log(point)
        } else {
          alert('您选择的地址没有解析到结果！')
        }
      }, '四川省')
    },
    getAreaList() {
      if (this.dataForm.enterpriseAddressId !== null) {
        getInfo(this.dataForm.enterpriseAddressId).then(res => {
          const addressObj = res.data.obj
          if (addressObj) {
            this.dataForm.enterpriseCityId = addressObj.parentid
            // this.selectDistrict(addressObj.parentid)
            getList({ parentid: addressObj.parentid }).then(res => {
              this.districtList = res.data.list
            })
            getInfo(addressObj.parentid).then(res => {
              this.dataForm.addressPId = res.data.obj.parentid
              //  this.selectCity(res.data.obj.parentid)
              getList({ parentid: res.data.obj.parentid }).then(res => {
                this.cityList = res.data.list
              })
            })
          }
        })
      }
      getList({ parentid: 0 }).then(res => {
        this.provinceList = res.data.list
      })
    },
    selectCity(val) {
      getList({ parentid: val }).then(res => {
        this.cityList = res.data.list
        this.dataForm.enterpriseCityId = ''
        this.dataForm.enterpriseAddressId = ''
      })
    },
    selectDistrict(val) {
      getList({ parentid: val }).then(res => {
        this.districtList = res.data.list
        this.dataForm.enterpriseAddressId = ''
      })
    },
    initData() {
      this.saveLoading = false
      this.formLoading = true
      if (this.obj) {
        this.dataForm = JSON.parse(JSON.stringify(this.obj))
        this.coordinate = this.dataForm.enterpriseLocation
        this.enterpriseAddressDetails = this.dataForm.enterpriseAddressDetails
      }
      this.getAreaList()
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      setTimeout(() => {
        this.formLoading = false
      }, 500)
    },
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          if (this.dataForm.id) {
            edit(this.dataForm).then(() => {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            })
          } else {
            add(this.dataForm).then(() => {
              this.$message.success('添加成功')
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            })
          }
        }
      })
    },
    closeDialog() {
      this.$emit('closeDialog')
      this.clearData()
      this.$refs['form'].clearValidate()
    },
    clearData() {
      this.dataForm = {
        id: null,
        name: null,
        enterpriseShort: null,
        // projectDepartmentId: null,
        organizationCode: null,
        legalRepresentative: null,
        zipCode: null,
        fax: null,
        contacts: null,
        contactInformation: null,
        emissionType: null,
        controlLevel: null,
        industryCategory: null,
        enterpriseLocation: null,
        enterpriseAddressDetails: null,
        addressPId: null,
        enterpriseCityId: null,
        enterpriseAddressId: null
      }
      this.coordinate = ''
      this.enterpriseAddressDetails = ''
    },
    selectMap() {
      this.dataForm.enterpriseLocation = this.coordinate
      this.dataForm.enterpriseAddressDetails = this.enterpriseAddressDetails
      this.mapDialogVisible = false
    },
    setPonit(data) {
      this.coordinate = data.point.lng + ',' + data.point.lat
      const geoc = new BMap.Geocoder()
      const ponit = new BMap.Point(data.point.lng, data.point.lat)
      geoc.getLocation(ponit, (res) => {
        this.enterpriseAddressDetails = res.address
      })
    },
    addMarker() {
      if (this.dataForm.enterpriseLocation === '' || this.dataForm.enterpriseLocation === null) {
        return
      }
      const gps = this.dataForm.enterpriseLocation.split(',')
      this.$refs.map.addMarker(gps[0], gps[1])
    },
    removeOverlay() {
      this.$refs.map.removeOverlay()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
